import json
import random

from django.db import connection, transaction
from django.http import HttpResponse, JsonResponse
from rest_framework.decorators import api_view

from HelloWorld.experimentDetail import getRegion, getConstellation, getStationByExpId, getConstellationGroup, \
    getDeviceByNodeId, getSatsByconsId
from TestModel import models
from django.core import serializers
from django.utils import timezone
import numpy as np

from django.db.models import Q


@api_view(['GET'])
def getExperimentDetail(request, experiment_id):
    experiment = models.Experiment.objects.filter(id=experiment_id)
    data = json.loads(serializers.serialize("json", experiment))[0]["fields"]
    data["experimentId"] = experiment_id
    data["regionInfos"] = getRegion(experimentId=experiment_id)
    # movingNodes 对应ships
    data["movingNodes"] = []
    data["tleOrbitSatellites"] = getSatsByconsId(experimentId=experiment_id)
    data["constellationInfos"] = getConstellation(experiment_id)
    data["staticNodes"] = getStationByExpId(experiment_id)
    data["constellationGroupInfos"] = getConstellationGroup(experiment_id)
    data["externalIdBaseOfExperimentId"] = experiment_id << 32  # 实验ID偏移32位后的结果
    data["classicOrbitSatellites"] = []
    # data["constellationInfos"] = []
    # data["constellationGroupInfos"] = []
    # data["regionInfos"] =[]
    return_json = {
        "errorCode": 200,
        "errorMsg": "获取实验成功",
        "data": data

    }
    return JsonResponse(return_json, safe=False)
    # with open('D:\dev\DjangoTest\HelloWorld\HelloWorld\getConfig.json', encoding='utf-8') as f:
    #     settings = json.load(f)
    #     return JsonResponse(settings, safe=False)


@api_view(['GET'])
def getSpectrumConfig(request, experiment_id, cons_id):
    spectrumConfig = models.SpectrumConfig.objects.filter(experimentId=experiment_id, constellationId=cons_id)
    if len(spectrumConfig) != 0:
        result = json.loads(serializers.serialize("json", spectrumConfig))
        spectrum_temp = result[0]["fields"]
        spectrum_temp["fdbChCarries"] = eval(spectrum_temp["fdbChCarries"])
        spectrum_temp["fdbChPolar"] = eval(spectrum_temp["fdbChPolar"])
        spectrum_temp["fdbFec"] = eval(spectrum_temp["fdbFec"])
        spectrum_temp["fdbModcod"] = eval(spectrum_temp["fdbModcod"])
        spectrum_temp["fubChCarries"] = eval(spectrum_temp["fubChCarries"])
        spectrum_temp["fubChPolar"] = eval(spectrum_temp["fubChPolar"])
        spectrum_temp["fubFec"] = eval(spectrum_temp["fubFec"])
        spectrum_temp["fubModcod"] = eval(spectrum_temp["fubModcod"])
        spectrum_temp["udbChCarries"] = eval(spectrum_temp["udbChCarries"])
        spectrum_temp["udbChPolar"] = eval(spectrum_temp["udbChPolar"])
        spectrum_temp["udbFec"] = eval(spectrum_temp["udbFec"])
        spectrum_temp["udbModcod"] = eval(spectrum_temp["udbModcod"])
        spectrum_temp["uubChCarries"] = eval(spectrum_temp["uubChCarries"])
        spectrum_temp["uubChPolar"] = eval(spectrum_temp["uubChPolar"])
        spectrum_temp["uubFec"] = eval(spectrum_temp["uubFec"])
        spectrum_temp["uubModcod"] = eval(spectrum_temp["uubModcod"])
        dict = {
            "errorCode": 200,
            "data": {
                "spectrumConfig": spectrum_temp
            },
            "errorMsg": "频谱获取成功"
        }
        return JsonResponse(dict, safe=False)
    else:
        dict = {
            "errorCode": 0,
            "errorMsg": "频谱获取失败"
        }
        return JsonResponse(dict, safe=False)


@api_view(['POST'])
def saveSpectrumConfig(request):
    body = json.loads(request.body.decode('utf-8'))
    models.SpectrumConfig.objects.filter(experimentId=body["experimentId"]).delete()
    models.SpectrumConfig.objects.create(
        name=body["name"],
        experimentId=body["experimentId"],
        constellationId=body["constellationId"],
        uubChBw=body["uubChBw"],
        uubChNum=body["uubChNum"],
        uubBwTot=body["uubBwTot"],
        uubChCarries=body["uubChCarries"],
        uubChK=body["uubChK"],
        uubChPolar=body["uubChPolar"],
        uubModcod=body["uubModcod"],
        uubRolloff=body["uubRolloff"],
        udbChBw=body["udbChBw"],
        udbChNum=body["udbChNum"],
        udbBwTot=body["udbBwTot"],
        udbChCarries=body["udbChCarries"],
        udbChK=body["udbChK"],
        udbChPolar=body["udbChPolar"],
        udbModcod=body["udbModcod"],
        udbRolloff=body["udbRolloff"],
        fubChBw=body["fubChBw"],
        fubChNum=body["fubChNum"],
        fubBwTot=body["fubBwTot"],
        fubChCarries=body["fubChCarries"],
        fubChK=body["fubChK"],
        fubChPolar=body["fubChPolar"],
        fubModcod=body["fubModcod"],
        fubRolloff=body["fubRolloff"],
        fdbChBw=body["fdbChBw"],
        fdbChNum=body["fdbChNum"],
        fdbBwTot=body["fdbBwTot"],
        fdbChCarries=body["fdbChCarries"],
        fdbChK=body["fdbChK"],
        fdbChPolar=body["fdbChPolar"],
        fdbModcod=body["fdbModcod"],
        fdbRolloff=body["fdbRolloff"],
        uubFec=body["uubFec"],
        udbFec=body["udbFec"],
        fubFec=body["fubFec"],
        fdbFec=body["fdbFec"],
        uubFrequencyPoint=body["uubFrequencyPoint"],
        udbFrequencyPoint=body["udbFrequencyPoint"],
        fubFrequencyPoint=body["fubFrequencyPoint"],
        fdbFrequencyPoint=body["fdbFrequencyPoint"],
    )
    models.Experiment.objects.filter(id=body["experimentId"]).update(internalIdMax=body["id"])
    result = {
        "errorCode": 200,
        "errorMsg": "频谱保存成功"
    }
    return JsonResponse(result, safe=False)


@api_view(['POST'])
def addConstellationGroup(request, experiment_id):
    body = json.loads(request.body.decode('utf-8'))
    experimentId = body["experimentId"]
    id = body["id"]
    showName = body["showName"]
    group = models.ConstellationGroup.objects.filter(id=id).first()
    if group:
        group.showName = showName
        group.save()
    else:
        models.ConstellationGroup.objects.create(experimentId=experimentId,
                                                 showName=showName,
                                                 id=id,
                                                 isHighOrbitConstellationGroup=0)
        models.Experiment.objects.filter(id=experimentId).update(internalIdMax=id)
    result = {
        "errorCode": 200
    }

    return JsonResponse(result, safe=False)


@api_view(['POST'])
def deleteConstellationGroupList(request):
    body = json.loads(request.body.decode('utf-8'))
    idList = body["idList"]
    for id in idList:
        with transaction.atomic():
            constellation = models.Constellation.objects.filter(constellationGroupId=id)
            for con in constellation:
                # 删除频谱
                models.SpectrumConfig.objects.filter(constellationId=con.id).delete()
                # 删除星座下的卫星
                satelllites = models.Satellite.objects.filter(constellationId=con.id)
                for satelllite in satelllites:
                    satid = satelllite.id
                    satelllite.delete()
                    models.Device.objects.filter(nodeId=satid).delete()
                models.Constellation.objects.filter(id=con.id).delete()
            # 删除卫星
            satelllites = models.Satellite.objects.filter(constellationGroupId=id)
            for satelllite in satelllites:
                satid = satelllite.id
                satelllite.delete()
                models.Device.objects.filter(nodeId=satid).delete()
            # 删除分区
            with connection.cursor() as cursor:
                select = f"select region_id from ground_region where json_extract(region_info_list,'$.parentId') = {id} "
                cursor.execute(select)
                regions = cursor.fetchall()
                # 删除分区下的设备和节点
                for region in regions:
                    regionId = region[0]
                    nodeid = models.Facility.objects.filter(regionId=regionId).values('id')
                    for idListinto in nodeid:
                        nodeid = idListinto["id"]
                        models.Device.objects.filter(nodeId=nodeid).delete()
                    models.Facility.objects.filter(regionId=regionId).delete()
                    models.GroundRegion.objects.filter(regionId=regionId).delete()
            facilitys = models.Facility.objects.filter(constellationGroupId=id)
            for fac in facilitys:
                models.Device.objects.filter(nodeId=fac.id).delete()
                fac.delete()
            # 删除星座组
            models.ConstellationGroup.objects.filter(id=id).delete()
    result = {
        "errorCode": 200
    }
    return JsonResponse(result, safe=False)


@api_view(['POST'])
def addConstellation(request):
    body = json.loads(request.body.decode('utf-8'))
    experimentId = body["experimentId"]
    constellationInfo = body["constellationInfo"]
    internalIdMax = body["internalIdMax"]
    # todo 添加事务
    with transaction.atomic():
        sat_list = []
        for sat in constellationInfo["satellites"]:
            sat_list.append(models.Satellite(
                id=sat["id"],
                showName=sat["showName"],
                nodeType=sat["nodeType"],
                _apogeeAltitude=sat["_apogeeAltitude"],
                _perigeeAltitude=sat["_perigeeAltitude"],
                inclination=sat["inclination"],
                argOfPerigee=sat["argOfPerigee"],
                raan=sat["raan"],
                trueAnomaly=sat["trueAnomaly"],
                attitudeSeg=sat["attitudeSeg"],
                constraintOffset=sat["constraintOffset"],
                isMainSatellite=sat["isMainSatellite"],
                constellationId=sat["constellationId"],
                planeIndex=sat["planeIndex"],
                interPlaneIndex=sat["interPlaneIndex"],
                deviceNumberLimit=sat["deviceNumberLimit"],
                experimentId=experimentId,
                constellationGroupId=sat["constellationGroupId"],
                tle1=sat["tle1"],
                tle2=sat["tle2"]
            ))
        models.Satellite.objects.bulk_create(sat_list)
        models.Constellation.objects.create(
            id=constellationInfo["id"],
            showName=constellationInfo["showName"],
            nodeType=constellationInfo["nodeType"],
            numberOfPlanes=constellationInfo["numberOfPlanes"],
            numberOfSatsPerPlane=constellationInfo["numberOfSatsPerPlane"],
            trueAnomalyInterval=0,
            raanSpread=constellationInfo["raanSpread"],
            experimentId=experimentId,
            zoningStatus=0,
            constellationGroupId=constellationInfo["constellationGroupId"],
            _perigeeAltitude=constellationInfo["_perigeeAltitude"],
            _apogeeAltitude=constellationInfo["_apogeeAltitude"],
            inclination=constellationInfo["inclination"],
            raan=constellationInfo["raan"],
            constellationType=constellationInfo["constellationType"],
            argOfPerigee=constellationInfo["argOfPerigee"],
            trueAnomaly=constellationInfo["trueAnomaly"]
        )
        models.Experiment.objects.filter(id=experimentId).update(internalIdMax=internalIdMax)
    result = {
        "errorCode": 200,
        "errorMsg": "插入成功"
    }
    return JsonResponse(result, safe=False)


@api_view(['POST'])
def deleteConstellation(request):
    body = json.loads(request.body.decode('utf-8'))
    experimentId = body["experimentId"]
    id = body["id"]
    models.SpectrumConfig.objects.filter(constellationId=id).delete()
    models.Constellation.objects.filter(id=id).delete()
    satelllites = models.Satellite.objects.filter(constellationId=id)
    for satelllite in satelllites:
        id = satelllite.id
        satelllite.delete()
        models.Device.objects.filter(nodeId=id).delete()
    result = {
        "errorCode": 200,
        "errorMsg": "删除星座成功"
    }
    return JsonResponse(result, safe=False)


@api_view(['POST'])
def modifyConstellationName(request):
    body = json.loads(request.body.decode('utf-8'))
    showName = body["showName"]
    id = body["id"]
    models.Constellation.objects.filter(id=id).update(showName=showName)
    result = {
        "errorCode": 200,
        "errorMsg": "修改星座名成功"
    }
    return JsonResponse(result, safe=False)


@api_view(['POST'])
def modifyNodeDeviceList(request):
    body = json.loads(request.body.decode('utf-8'))
    devices = body["devices"]
    targetId = body["targetId"]
    internalIdMax = body["internalIdMax"] + 1
    experimentId = body["experimentId"]
    targetType = body["targetType"]
    if targetType == "constellation":
        targets = models.Satellite.objects.filter(constellationId=targetId)
    if targetType == "region":
        targets = models.Facility.objects.filter(regionId=targetId)
    for tr in targets:
        models.Device.objects.filter(devicePatternId=targetId).delete()
        device_list = []
        for device in devices.values():
            if device is not None:
                # ID 问题还需要处理
                deviceEquipConfig = device["deviceEquipConfig"]
                linkConfig = device["linkConfig"]
                receiver = device["receiver"]
                transmitter = device["transmitter"]
                device_temp = models.Device(
                    nodeId=tr.id,
                    id=internalIdMax,
                    devicePatternId=0,  # 后续可能还要修改
                    deviceName=device["deviceName"],
                    deviceType=device["deviceType"],
                    azimuth=deviceEquipConfig["azimuth"],
                    elevation=deviceEquipConfig["elevation"],
                    maxAzimuth=deviceEquipConfig["maxAzimuth"],
                    maxElevation=deviceEquipConfig["maxElevation"],
                    minAzimuth=deviceEquipConfig["minAzimuth"],
                    minElevation=deviceEquipConfig["minElevation"],
                    pointingType=deviceEquipConfig["pointingType"],
                    antennaReGain=receiver["antennaReGain"],
                    aptLoss=receiver["aptLoss"],
                    fNoiseTemperature=receiver["fNoiseTemperature"],
                    otherReGainLoss=receiver["otherReGainLoss"],
                    reEfficiency=receiver["reEfficiency"],
                    antennaTrGain=transmitter["antennaTrGain"],
                    beamDistribution=transmitter["antennaTrGain"],
                    diameter=transmitter["antennaTrGain"],
                    diffractionLimit=transmitter["antennaTrGain"],
                    divergenceAngle=transmitter["antennaTrGain"],
                    otherTrGainLoss=transmitter["antennaTrGain"],
                    trEfficiency=transmitter["antennaTrGain"],
                    trPower=transmitter["antennaTrGain"]
                )
                if device["deviceType"] == 1:
                    device_temp.maxRange = deviceEquipConfig["maxRange"]
                    device_temp.bandWidth = linkConfig["bandWidth"]
                    device_temp.communication = linkConfig["communication"]
                    device_temp.communicationSpeed = linkConfig["communicationSpeed"]
                    device_temp.modulationMode = linkConfig["modulationMode"]
                    device_temp.waveLength = linkConfig["waveLength"]
                    device_temp.receiveThreshold = receiver["receiveThreshold"]
                    device_temp.trackingError = receiver["trackingError"]
                else:
                    device_temp.beamFov = deviceEquipConfig["beamFov"]
                    device_temp.dbeamNum = deviceEquipConfig["azimuth"]
                    device_temp.halfAngleMajorAxis = deviceEquipConfig["halfAngleMajorAxis"]
                    device_temp.halfAngleMinorAxis = deviceEquipConfig["halfAngleMinorAxis"]
                    device_temp.modulationMode = linkConfig["modulationMode"]
                    device_temp.lnbGain = receiver["lnbGain"]
                    device_temp.maxDepoint = receiver["maxDepoint"]
                    device_temp.bUtil = transmitter["bUtil"]
                    device_temp.backoff = transmitter["backoff"]
                    device_temp.contour = transmitter["contour"]
                    device_temp.fec = transmitter["fec"]
                    device_temp.freq = transmitter["freq"]
                    device_temp.otherTrGainLoss = transmitter["otherTrGainLoss"]
                    device_temp.polarizationMode = transmitter["polarizationMode"]
                    device_temp.radiationModel = transmitter["radiationModel"]
                    device_temp.rolloff = transmitter["rolloff"]
                device_list.append(device_temp)
                internalIdMax += 1
        models.Device.objects.bulk_create(device_list)
        models.Experiment.objects.filter(id=experimentId).update(internalIdMax=internalIdMax)
    result = {
        "errorCode": 200,
        "data": {
            "internalIdMax": internalIdMax,
        }
    }
    return JsonResponse(result, safe=False)


# 分区
@api_view(['POST'])
def modifyGroundRegionAndTerminal(request):
    body = json.loads(request.body.decode('utf-8'))
    regionInfo = body['regionInfo']
    terminals = regionInfo["terminals"],
    models.GroundRegion.objects.filter(regionId=regionInfo["id"]).delete()
    models.Facility.objects.filter(regionId=regionInfo["id"]).delete()
    with transaction.atomic():
        models.GroundRegion.objects.create(
            regionId=regionInfo["id"],
            experimentId=body["experimentId"],
            regionInfoList=body["regionInfo"],
            internalIdMax=body["internalIdMax"],
            lastModTime=timezone.now().strftime("%Y-%m-%d %H:%M:%S")  # 时间输出有问题
        )

        for facility in terminals:
            for terminal in facility:
                position = terminal["position"]
                models.Facility.objects.create(
                    id=terminal["id"],
                    showName=terminal["showName"],
                    nodeType=terminal["nodeType"],
                    latitude=position["latitude"],
                    longitude=position["longitude"],
                    altitude=position["altitude"],
                    experimentId=body["experimentId"],
                    constellationGroupId=terminal["constellationGroupId"],
                    grade=terminal["grade"],
                    bwReq=terminal["bwReq"],
                    regionId=regionInfo["id"],
                )
    result = {
        "errorCode": 200
    }
    return JsonResponse(result, safe=False)


@api_view(['POST'])
def deleteGroundRegionAndTerminal(request):
    body = json.loads(request.body.decode('utf-8'))
    regionIdList = body["regionIdList"]
    for regionid in regionIdList:
        models.GroundRegion.objects.filter(regionId=regionid).delete()
        nodeid = models.Facility.objects.filter(regionId=regionid).values('id')
        for idListinto in nodeid:
            nodeid = idListinto["id"]
            models.Device.objects.filter(nodeId=nodeid).delete()
        models.Facility.objects.filter(regionId=regionid).delete()
    result = {
        "errorCode": 200
    }
    return JsonResponse(result, safe=False)


def modifyNode(request):
    body = json.loads(request.body.decode('utf-8'))
    data = body["data"]
    internalIdMax = body["internalIdMax"]
    experimentId = body["experimentId"]

    modifyDataType = body["modifyDataType"]
    if modifyDataType == 0:
        models.Facility.objects.filter(id=data["id"]).delete()
        if data["nodeType"] == 1:
            models.Satellite.objects.filter(id=data["id"]).delete()
            models.Satellite.objects.create(
                id=data["id"],
                showName=data["showName"],
                nodeType=data["nodeType"],
                attitudeSeg=data["attitudeSeg"],
                constraintOffset=data["constraintOffset"],
                isMainSatellite=data["isMainSatellite"],
                constellationId=0,
                deviceNumberLimit=data["deviceNumberLimit"],
                experimentId=experimentId,
                constellationGroupId=data["parentId"],
                tle1=data["tle1"],
                tle2=data["tle2"]
            )
        else:
            position = data["position"]
            models.Facility.objects.create(
                id=data["id"],
                showName=data["showName"],
                nodeType=data["nodeType"],
                latitude=position["latitude"],
                longitude=position["longitude"],
                altitude=position["altitude"],
                experimentId=body["experimentId"],
                attitudeSeg=data["attitudeSeg"],
                accessConstellationList=data["accessConstellationList"],
                constellationGroupId=data["parentId"],
                grade=data["grade"],
                bwReq=data["bwReq"],
            )

    if modifyDataType == 1:
        communicationDevices = data["communicationDevices"]
        IdList = []
        i = 0
        while i < len(communicationDevices):
            id = communicationDevices[i]["id"]
            deviceEquipConfig = communicationDevices[i]["deviceEquipConfig"]
            linkConfig = communicationDevices[i]["linkConfig"]
            transmitter = communicationDevices[i]["transmitter"]
            receiver = communicationDevices[i]["receiver"]

            IdList.append(id)
            models.Facility.objects.filter(id=data["id"]).update(deviceId=IdList)

            models.Device.objects.filter(id=id).delete()
            models.Device.objects.create(
                id=id,
                nodeId=data["id"],
                deviceName=communicationDevices[i]["deviceName"],
                devicePatternId=0,
                experimentId=body["experimentId"],
                deviceType=communicationDevices[i]["deviceType"],
                # deviceNumber=,
                pointingType=deviceEquipConfig["pointingType"],
                azimuth=deviceEquipConfig["azimuth"],
                elevation=deviceEquipConfig["elevation"],
                minAzimuth=deviceEquipConfig["minAzimuth"],
                maxAzimuth=deviceEquipConfig["maxAzimuth"],
                minElevation=deviceEquipConfig["minElevation"],
                maxElevation=deviceEquipConfig["maxElevation"],
                trPower=transmitter["trPower"],
                diameter=transmitter["diameter"],
                trEfficiency=transmitter["trEfficiency"],
                antennaTrGain=transmitter["antennaTrGain"],
                otherTrGainLoss=transmitter["otherTrGainLoss"],
                modulationMode=linkConfig["modulationMode"],
                reEfficiency=receiver["reEfficiency"],
                antennaReGain=receiver["antennaReGain"],
                otherReGainLoss=receiver["otherReGainLoss"],
                fNoiseTemperature=receiver["fNoiseTemperature"],
                aptLoss=receiver["aptLoss"]
            )

            if communicationDevices[i]["deviceType"] == 1:
                models.Device.objects.filter(id=id).update(
                    waveLength=linkConfig["waveLength"],
                    bandWidth=linkConfig["bandWidth"],
                    communicationSpeed=linkConfig["communicationSpeed"],
                    divergenceAngle=transmitter["divergenceAngle"],
                    beamDistribution=transmitter["beamDistribution"],
                    diffractionLimit=transmitter["diffractionLimit"],
                    receiveThreshold=receiver["receiveThreshold"],
                    trackingError=receiver["trackingError"],
                )
            elif communicationDevices[i]["deviceType"] == 4 or communicationDevices[0]["deviceType"] == 5:
                models.Device.objects.filter(id=id).update(
                    ubeamNum=deviceEquipConfig["ubeamNum"],
                    beamFov=deviceEquipConfig["beamFov"],
                    halfAngleMinorAxis=deviceEquipConfig["halfAngleMinorAxis"],
                    halfAngleMajorAxis=deviceEquipConfig["halfAngleMajorAxis"],
                    dbeamNum=deviceEquipConfig["dbeamNum"],
                    lnbGain=receiver["lnbGain"],
                    maxDepoint=receiver["maxDepoint"],
                    fec=transmitter["fec"],
                    bUtil=transmitter["bUtil"],
                    freq=transmitter["freq"],
                    backoff=transmitter["backoff"],
                    contour=transmitter["contour"],
                    rolloff=transmitter["rolloff"],
                    polarizationMode=transmitter["polarizationMode"],
                    radiationModel=transmitter["radiationModel"]
                )
            i += 1

    models.Experiment.objects.filter(id=experimentId).update(internalIdMax=internalIdMax)
    result = {
        "errorCode": 200
    }

    return JsonResponse(result, safe=False)


def deleteNodeList(request):
    body = json.loads(request.body.decode('utf-8'))
    nodeIdAndTypes = body["nodeIdAndTypes"]
    # experimentId=body["experimentId"]
    # print(body["nodeIdAndTypes"])
    for nodeIdList1 in nodeIdAndTypes:
        for key in nodeIdList1:
            datakey = 'nodeIds'
            if key == datakey:
                value = nodeIdList1[key]
                for id in value:
                    models.Facility.objects.filter(id=id).delete()
    result = {
        "errorCode": 200
    }
    return JsonResponse(result, safe=False)


@api_view(['POST'])
def modifyDevicePattern(request):
    body = json.loads(request.body.decode('utf-8'))
    device_pattern_id = body["devicePattern"]["devicePatternId"]
    device_pattern_name = body["devicePattern"]["devicePatternName"]
    experiment_id = body["experimentId"]
    device = body["devicePattern"]["devices"][0]
    # deviceEquipConfig
    device_name = device["deviceName"]
    device_type = device["deviceType"]
    id = device["id"]
    # EquipConfig
    deviceEquipConfig = device["deviceEquipConfig"]
    # linkconfig
    linkConfig = device["linkConfig"]
    # receiver
    receiver = device["receiver"]
    # transmitter
    transmitter = device["transmitter"]
    # print(device_type)
    internalIdMax = body["internalIdMax"]
    models.Device.objects.filter(id=id).delete()
    models.DevicePattern.objects.filter(id=device_pattern_id).delete()
    if device_type == 1:
        models.Device.objects.create(devicePatternId=device_pattern_id,
                                     experimentId=experiment_id,
                                     deviceName=device_name,
                                     deviceType=device_type,
                                     id=id,
                                     azimuth=deviceEquipConfig["azimuth"],
                                     elevation=deviceEquipConfig["elevation"],
                                     maxAzimuth=deviceEquipConfig["maxAzimuth"],
                                     maxElevation=deviceEquipConfig["maxElevation"],
                                     minAzimuth=deviceEquipConfig["minAzimuth"],
                                     minElevation=deviceEquipConfig["minElevation"],
                                     pointingType=deviceEquipConfig["pointingType"],
                                     maxRange=deviceEquipConfig["maxRange"],

                                     bandWidth=linkConfig["bandWidth"],
                                     communication=linkConfig["communication"],
                                     communicationSpeed=linkConfig["communicationSpeed"],
                                     modulationMode=linkConfig["modulationMode"],
                                     waveLength=linkConfig["waveLength"],

                                     antennaReGain=receiver["antennaReGain"],
                                     aptLoss=receiver["aptLoss"],
                                     fNoiseTemperature=receiver["fNoiseTemperature"],
                                     otherReGainLoss=receiver["otherReGainLoss"],
                                     reEfficiency=receiver["reEfficiency"],
                                     receiveThreshold=receiver["receiveThreshold"],
                                     trackingError=receiver["trackingError"],

                                     beamDistribution=transmitter["beamDistribution"],
                                     diameter=transmitter["diameter"],
                                     diffractionLimit=transmitter["diffractionLimit"],
                                     divergenceAngle=transmitter["divergenceAngle"],
                                     otherTrGainLoss=transmitter["otherTrGainLoss"],
                                     trEfficiency=transmitter["trEfficiency"],
                                     trPower=transmitter["trPower"],
                                     )
        models.DevicePattern.objects.create(id=device_pattern_id,
                                            devicePatternName=device_pattern_name,
                                            experimentId=experiment_id,
                                            # create_time="2023-01-25 10:44:50",
                                            # update_time = "2023-01-25 10:44:50"
                                            )
        models.Experiment.objects.filter(id=experiment_id).update(internalIdMax=internalIdMax)
    else:

        models.Device.objects.create(devicePatternId=device_pattern_id,
                                     experimentId=experiment_id,
                                     deviceName=device_name,
                                     deviceType=device_type,
                                     id=id,
                                     azimuth=deviceEquipConfig["azimuth"],
                                     elevation=deviceEquipConfig["elevation"],
                                     maxAzimuth=deviceEquipConfig["maxAzimuth"],
                                     maxElevation=deviceEquipConfig["maxElevation"],
                                     modulationMode=linkConfig["modulationMode"],
                                     minAzimuth=deviceEquipConfig["minAzimuth"],
                                     minElevation=deviceEquipConfig["minElevation"],
                                     pointingType=deviceEquipConfig["pointingType"],
                                     beamFov=deviceEquipConfig["beamFov"],
                                     dbeamNum=deviceEquipConfig["dbeamNum"],
                                     halfAngleMajorAxis=deviceEquipConfig["halfAngleMajorAxis"],
                                     halfAngleMinorAxis=deviceEquipConfig["halfAngleMinorAxis"],
                                     ubeamNum=deviceEquipConfig["ubeamNum"],

                                     antennaReGain=receiver["antennaReGain"],
                                     aptLoss=receiver["aptLoss"],
                                     fNoiseTemperature=receiver["fNoiseTemperature"],
                                     lnbGain=receiver["lnbGain"],
                                     maxDepoint=receiver["maxDepoint"],
                                     otherReGainLoss=receiver["otherReGainLoss"],
                                     reEfficiency=receiver["reEfficiency"],

                                     antennaTrGain=transmitter["antennaTrGain"],
                                     bUtil=transmitter["bUtil"],
                                     backoff=transmitter["backoff"],
                                     contour=transmitter["contour"],
                                     diameter=transmitter["diameter"],
                                     fec=transmitter["fec"],
                                     freq=transmitter["freq"],
                                     otherTrGainLoss=transmitter["otherTrGainLoss"],
                                     polarizationMode=transmitter["polarizationMode"],
                                     radiationModel=transmitter["radiationModel"],
                                     rolloff=transmitter["rolloff"],
                                     trEfficiency=transmitter["trEfficiency"],
                                     trPower=transmitter["trPower"],
                                     )
        models.DevicePattern.objects.create(id=device_pattern_id,
                                            devicePatternName=device_pattern_name,
                                            experimentId=experiment_id,
                                            # create_time="2023-01-25 10:44:50",
                                            # update_time = "2023-01-25 10:44:50"
                                            )
        models.Experiment.objects.filter(id=experiment_id).update(internalIdMax=internalIdMax)
    result = {
        "errorCode": 200
    }
    return JsonResponse(result, safe=False)


@api_view(['POST'])
def deleteDevicePattern(request):
    body = json.loads(request.body.decode('utf-8'))
    device_pattern_id = body["devicePatternIds"][0]
    experiment_id = body["experimentId"]
    # internalIdMax = body["internalIdMax"]
    models.Device.objects.filter(devicePatternId=device_pattern_id).delete()
    models.DevicePattern.objects.filter(id=device_pattern_id).delete()
    # models.Experiment.objects.filter(id=experiment_id).update(internalIdMax=internalIdMax)
    result = {
        "errorCode": 200
    }
    return JsonResponse(result, safe=False)


@api_view(['GET'])
def getDevicePattern(request, experiment_id):
    id = request.GET.get('experiment_id')
    device_pattern = models.DevicePattern.objects.filter(experimentId=experiment_id)
    result = json.loads(serializers.serialize("json", device_pattern))
    device_pattern_list = []
    for res in result:
        device_pattern_temp = res["fields"]
        device_pattern_temp["devicePatternId"] = res["pk"]
        device_pattern_temp["devices"] = getDeviceByNodeId(res["pk"], 2)
        device_pattern_list.append(device_pattern_temp)
    dict = {
        "errorCode": 200,
        "data": {
            "devicePatterns": device_pattern_list
        }
    }
    # 这里出问题了，只打印了循环的最后一个，应该是把那个循环的所有结果保存在一个列表中，，放到list中了，但是不知道为啥还报错了
    # 列表里是所有实验id对应的设备模板，但前端还会执行说获取列表模板失败，那个语句是什么意思？数据格式不对？
    return JsonResponse(dict, safe=False)


@api_view(['POST'])
def getNodeInfo(request):
    body = json.loads(request.body.decode('utf-8'))
    id = body["id"]
    nodeType = body["nodeType"]
    if nodeType == 1:
        node = models.Satellite.objects.filter(id=id)
    else:
        node = models.Facility.objects.filter(id=id)
    result = json.loads(serializers.serialize("json", node))
    data = result[0]["fields"]
    data["id"] = result[0]["pk"]
    dict = {
        "errorCode": 200,
        "data": data
    }
    return JsonResponse(dict, safe=False)


@api_view(['GET'])
def getDefaultConfig(request, config_id):
    # experimentId=experiment_id
    # print(config_id)
    if (config_id == 1 or config_id == 4 or config_id == 9):
        config = models.Device.objects.filter(id=config_id)
        if len(config) != 0:
            result = json.loads(serializers.serialize("json", config))
            data = result[0]["fields"]
            data["id"] = result[0]["pk"]
            dict = {
                "errorCode": 200,
                "data": data,
            }
            return JsonResponse(dict, safe=False)
        else:
            dict = {
                "errorCode": 0,
                "errorMsg": "获取设备失败"
            }
            return JsonResponse(dict, safe=False)

    else:
        config = models.SpectrumConfig.objects.filter(id=config_id)
        if len(config) != 0:
            result = json.loads(serializers.serialize("json", config))
            data = result[0]["fields"]
            data["id"] = result[0]["pk"]
            dict = {
                "errorCode": 200,
                "data": data,
            }
            return JsonResponse(dict, safe=False)
        else:
            dict = {
                "errorCode": 0,
                "errorMsg": "获取频谱失败"
            }
            return JsonResponse(dict, safe=False)


def getRegionPairList(request, experiment_id):
    id = request.GET.get("experiment_id")
    regionpair = models.RegionPairConfig.objects.filter(experimentId=experiment_id)
    result = json.loads(serializers.serialize("json", regionpair))
    regionpairList = []
    for res in result:
        region_pair_temp = res["fields"]
        regionpairList.append(region_pair_temp)
    result_dict = {
        "errorCode": 200,
        "data": {
            "regionPairs": regionpairList
        }
    }
    return JsonResponse(result_dict, safe=False)


def createRegionPairs(request):
    body = json.loads(request.body.decode('utf-8'))
    experimentId = body["experimentId"]
    regionPairs = body["regionPairs"]
    regionPairList = []
    routePairList = []
    for regionPair in regionPairs:
        models.RegionPairConfig.objects.filter(experimentId=experimentId).delete()
        repair = models.RegionPairConfig(
            experimentId=body["experimentId"],
            regionFirst=regionPair["regionFirst"],
            regionSecond=regionPair["regionSecond"],
            terminalPairNum=regionPair["terminalPairNum"],
            protoType=regionPair["protoType"],
            intervals=regionPair["interval"],
            packageSize=regionPair["package"],
            showName=regionPair["showName"],
            status=0
        )
        regionPairList.append(repair)

        regionInfoList1 = models.GroundRegion.objects.filter(regionId=regionPair["regionFirst"])
        regionInfoList2 = models.GroundRegion.objects.filter(regionId=regionPair["regionSecond"])
        regionInfo1 = json.loads(serializers.serialize("json", regionInfoList1))
        regionInfo2 = json.loads(serializers.serialize("json", regionInfoList2))
        regionResultList1 = []
        regionResultList2 = []
        for region in regionInfo1:
            regionInfo = region["fields"]
            regionResultList1.append(regionInfo)
        terminalNum1 = regionResultList1[0]["regionInfoList"]["terminalNum"]
        for region in regionInfo2:
            regionInfo = region["fields"]
            regionResultList2.append(regionInfo)
        terminalNum2 = regionResultList2[0]["regionInfoList"]["terminalNum"]
        i = 0
        while i < regionPair["terminalPairNum"]:
            id1 = random.randint(0, terminalNum1 - 1)
            id2 = random.randint(0, terminalNum2 - 1)
            #不建立重复路由
            if models.RouteDetail.regionFirst == regionPair["regionFirst"] and models.RouteDetail.regionSecond == \
                    regionPair["regionSecond"]:
                if id1 == models.RouteDetail.sourceNodeId and id2 == models.RouteDetail.sourceNodeId:
                    id1 = random.randint(0, terminalNum1 - 1)
                    id2 = random.randint(0, terminalNum2 - 1)
            terminal1 = regionResultList1[0]["regionInfoList"]["terminals"][id1]
            terminal2 = regionResultList2[0]["regionInfoList"]["terminals"][id2]
            models.RouteDetail.objects.filter(experimentId=experimentId).delete()
            routeRepair = models.RouteDetail(
                experimentId=body["experimentId"],
                regionFirst=regionPair["regionFirst"],
                regionSecond=regionPair["regionSecond"],
                protoType=regionPair["protoType"],
                intervals=regionPair["interval"],
                packageSize=regionPair["package"],
                status=0,
                sourceNodeId=terminal1["id"],
                targetNodeId=terminal2["id"],
                sourceNodeName=terminal1["showName"],
                targetNodeName=terminal2["showName"],
                selected=0
            )
            routePairList.append(routeRepair)
            i = i + 1
        models.RouteDetail.objects.bulk_create(routePairList)
    models.RegionPairConfig.objects.bulk_create(regionPairList)

    result = {
        "errorCode": 200
    }
    return JsonResponse(result, safe=False)
